package cn.nexttec.noteplayer.common

import java.nio.charset.Charset
import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec


object AESUtil {
    private const val ALGORITHM = "AES/CBC/PKCS5Padding"
    private const val AES = "AES"

    // IV 必须是 16 字节（128 位）
    private const val IV_STRING = "0123456123456789"
    @Throws(Exception::class)
    fun encrypt(plaintext: String, key: String = "NotePlayer"): String {
        require(key.length == 32) { "Key must be 32 characters (256 bits)" }
        val cipher = Cipher.getInstance(ALGORITHM)
        val keySpec = SecretKeySpec(key.toByteArray(), AES)
        val ivSpec = IvParameterSpec(IV_STRING.toByteArray())
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec)
        val encrypted = cipher.doFinal(plaintext.toByteArray(charset("UTF-8")))
        return Base64.getEncoder().encodeToString(encrypted)
    }

    @Throws(Exception::class)
    fun decrypt(ciphertext: String?,key: String = "NotePlayer"): String {
        val cipher = Cipher.getInstance(ALGORITHM)
        val keySpec = SecretKeySpec(key.toByteArray(), AES)
        val ivSpec = IvParameterSpec(IV_STRING.toByteArray())
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec)
        val decoded = Base64.getDecoder().decode(ciphertext)
        val original = cipher.doFinal(decoded)
        return String(original, Charset.forName("UTF-8"))
    }
}
